<template>
  <div class='orderinfoContainer'>
    <!-- 采购确认弹框 -->
    <pur-in-store v-if="receiveDialog" @closeDialog="closeDialog" :purItemBatchList='purItemBatchList'
                  :shopinfo="entityInfo"></pur-in-store>
    <!-- 入库详情弹框 -->
    <warehouse-detail v-if="putStorageDialog" @closeDialog="closeDialog" :houseDetail='houseDetail'></warehouse-detail>
    <div class='orderInfo'>
      <div class="detail-order">
        <div class="iconStyle">
          <i class="iconfont" style="color:#409eff">&#xe693;</i><span>订单详情</span>
        </div>
        <v-form :formProps="orderDetailForm" ref="orderDetailForm"></v-form>
        <v-table :tableParams="purchaseItemTable"></v-table>
      </div>
      <div class="detail-order">
        <div class="iconStyle">
          <i class="iconfont" style="color:#409eff;margin-left:10px">&#xe646;</i><span>审批信息</span>
        </div>
        <v-table :tableParams="approvalTable"></v-table>
      </div>
      <div class="detail-order">
        <div class="iconStyle">
          <i class="iconfont" style="color:#409eff;margin-left:10px">&#xe88f;</i><span>收货信息</span>
        </div>
        <v-table :tableParams="receiveGoodTable" v-on:handleOperation="handleOperation"></v-table>
      </div>
      <div class="detail-order">
        <div class="iconStyle">
          <i class="iconfont" style="color:#409eff;margin-left:10px">&#xe67f;</i><span>采购合同</span>
        </div>
        <v-table :tableParams="contactTable" v-on:handleOperation="operation"></v-table>
      </div>

      <div class="confirm">
        <el-button @click="goBack" size="medium">返回列表</el-button>
        <el-button type="success" @click="buyAudit"
                   v-if="entityInfo.purBillsType === '1' && this.approval " size="medium">初审审批
        </el-button>
        <el-button type="success" @click="overAudit"
                   v-if="entityInfo.purBillsType === '2' && this.approval" size="medium">终审审批
        </el-button>
        <el-button type="primary" @click="generate" size="medium" v-if="approveState === '1' && approveType ==='终审' ">生成采购合同</el-button>
        <el-button @click="btnConfirm" v-if="entityInfo.purBillsType === '4' && entityInfo.userId+'' === userId+''"
                   type="primary" size="medium">确认收货
        </el-button>
      </div>
    </div>
    <!-- //初审审批弹框 -->
    <div class="dialog" v-if="auditDialog">
      <div class="dialog-con firstAudit">
        <div class="firstAuditTitle">审批</div>
        <div class="opinion">
          <v-form :formProps="editForm" ref="form"
                  v-on:handleReset="handleReset"
                  v-on:coverFormData="submitForm"></v-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import {localStorage} from 'js/localStorage'
  import axios from 'axios'
  import PurInStore from 'components/base/PurInStore'
  import VTable from "components/common/PageTable/VTable"
  import VForm from "components/common/VForm"
  import warehouseDetail from 'components/base/WarehouseDetail'

  const purOrderTypeData = {
    '1': '常规订单',
    '2': '集采订单',
    '3': '天猫订单'
  };
  export default {
    components: {
      PurInStore, warehouseDetail, VTable, VForm
    },
    data() {
      return {
        entityInfo: {},
        orderDetailForm: {
          showOperationBtn: false,
          col: 4,
          labelWidth: '120px',
          formItemArray: [{
            label: '订单类型',
            readonly: true,
            prop: 'purOrderType',
            value: ''
          }, {
            label: '单据(合同)编号',
            readonly: true,
            prop: 'purBillsId',
            value: ''
          }, {
            label: '订单金额',
            readonly: true,
            prop: 'price',
            value: ''
          }, {
            label: '预计到货日期',
            readonly: true,
            prop: 'predictTime',
            value: ''
          }, {
            label: '订单日期',
            readonly: true,
            prop: 'purBillsDate',
            value: ''
          }, {
            label: '采购公司',
            readonly: true,
            prop: 'companyName',
            value: ''
          }, {
            label: '供应商名称',
            readonly: true,
            prop: 'supplyName',
            value: ''
          },{
            label: '供应商联系人',
            readonly: true,
            prop: 'supplyContact',
            value: ''
          },{
            label: '供应商联系方式',
            readonly: true,
            prop: 'supplyMobile',
            value: ''

          }, {
            label: '收货仓库',
            readonly: true,
            prop: 'depotName',
            value: ''
          }],
        }, purchaseItemTable: {
          operationColumnWidth: 180,
          dataArray: [],
          showMultiSelection: false,
          showOperationColumn: false,
          columnArray: [
            {label: '商品名称', prop: 'productName', sortable: false},
            {label: '商品品牌', prop: 'brandCode', sortable: false},
            {label: '商品编码', prop: 'productNo', sortable: false},
            {label: '重量', prop: 'productWeight', sortable: false},
            {label: '进货价(含税运)', prop: 'purchasePrice', sortable: false,width:'120'},
            {label: '采购单价', prop: 'productPrice', sortable: false},
            {label: '采购数量', prop: 'purNumber', sortable: false},
            {label: '采购金额', prop: 'money', sortable: false},
            {label: '其他费用', prop: 'elsePrice', sortable: false},
            {label: '总费用', prop: 'totalPrice', sortable: false},
            {label: '备注', prop: 'memo', sortable: false},
          ],
          rowHandle: {}
        },
        approvalTable: {
          operationColumnWidth: 180,
          dataArray: [],
          showMultiSelection: false,
          showOperationColumn: false,
          columnArray: [
            {label: '发起时间', prop: 'createtime', sortable: false},
            {label: '申请人', prop: 'applyName', sortable: false},
            {label: '审批人', prop: 'username', sortable: false},
            {label: '审批时间', prop: 'updatetime', sortable: false},
            {label: '审批状态', prop: 'approveState', sortable: false},
            {label: '审批类型', prop: 'approveType', sortable: false},
            {label: '审批意见', prop: 'memo', sortable: false},
          ],
          rowHandle: {}
        },
        receiveGoodTable: {
          operationColumnWidth: 100,
          dataArray: [],
          showMultiSelection: false,
          columnArray: [
            {label: '单据合同编号', prop: 'purBillsId', sortable: false},
            {label: '商品名称', prop: 'productName', sortable: false},
            {label: '商品编码', prop: 'productCode', sortable: false},
            {label: '应入库数', prop: 'purNumber', sortable: false},
            {label: '已入库数', prop: 'totalCount', sortable: false},
          ],
          rowHandle: {
            update: {show: false},
            deleted: {show: false},
            view: {'text': '查看入库详情'}
          }
        },
        contactTable:{
          operationColumnWidth: 100,
          dataArray: [],
          showMultiSelection: false,
          columnArray: [
            {label: '文件名字', prop: 'fileName', sortable: false},
            {label: '上传人', prop: 'userName', sortable: false},
            {label: '上传时间', prop: 'createdTime', sortable: false}

          ],
          rowHandle: {
            update: {show: false},
            deleted: {show: true},
            view:{show:false}

          }
        },
        editForm: {
          resetBtn: {
            text: '取消',
          },
          col: 1,
          labelWidth: '90px',
          formItemArray: [{
            label: '审批结果',
            placeholder: "请选择",
            rules: [{required: true, message: '请选择审批结果', trigger: 'change'}],
            prop: 'approveState',
            itemType: 'select',
            options: [
              {value: '1', label: '通过'},
              {value: '2', label: '驳回'}
            ],
            value: ''
          }, {
            label: '审批意见',
            prop: 'memo',
            itemType: 'textarea',
            value: ''
          },]
        },
        purItemBatchList: [],
        purBillsId: '',
        userId: '',
        receiveDialog: false,
        putStorageDialog: false,
        auditDialog: false,
        approval: null,
        approveState:'',
        approveType:''
      }

    },
    created() {
      this.userId = localStorage.get("userID")
      this.init()
      //采购合同的接口
      this.purchaseContact()
    },
    methods: {
      init() {
        let param = {
          userId: this.userId,
          purBillsId: this.$route.query.purBillsId
        }
        let success = data => {
          if (data.code === 'OK') {
            this.entityInfo = Object.assign({}, data.data.entity);
            this.orderDetailForm.formItemArray.forEach(item => {
              for (let key in this.entityInfo) {
                if (key === item.prop) {
                  let value = this.entityInfo[key];
                  if (item.prop === 'predictTime' || item.prop === 'purBillsDate') {
                    item.value = this.formatSystemDate(value);
                  } else if (item.prop === 'purOrderType') {
                    item.value = purOrderTypeData[value];
                  } else {
                    item.value = value;
                  }
                }
              }
            });
            this.purchaseItemTable.dataArray = data.data.itemList;
            this.purchaseItemTable.dataArray.forEach(item => {
              item.totalPrice = item.money;
              if (item.elsePrice) {
                item.totalPrice = this.calculate.operation(item.money, item.elsePrice, '+');
              }
            });

            this.approvalTable.dataArray = data.data.approveList;
            this.approvalTable.dataArray.forEach(item => {
              item.createtime = this.formatSystemDate(item.createtime);
              item.updatetime = this.formatSystemDate(item.updatetime);
              //
              this.approveState = item.approveState
              this.approveType=item.approveType

              switch (item.approveState) {
                case "0":
                  item.approveState = '待审';
                  break;
                case "1":
                  item.approveState = '通过';
                  break;
                case "2":
                  item.approveState = '驳回';
                  break;
                case "3":
                  item.approveState = '发起';
                  break;
              }
            });
            this.approval = data.data.approval;
            this.purItemBatchList = data.data.purItemBatchList;
            this.receiveGoodTable.dataArray = data.data.purItemBatchList;
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.buyPurListItemNew(param, success)
      },
      purchaseContact(){
        let parmas={
          serviceId:this.$route.query.id
        }
        let succ=data=>{
          if(data.code=="OK"){
            this.contactTable.dataArray=data.data
            data.data.forEach(element => {
              element.createdTime = this.formatSystemDate(element.createdTime);
            });
          }else{
            this.$message.error(data.msg)
          }
        }
        this.api.invoiceContactResource(parmas,succ)
      },
      goBack() {
        let query = {searchCondition: this.$route.query.searchCondition};
        this.$router.push({
          path: '/my-review',
          query: query
        });

      }
      ,
      //关闭确认收货弹窗
      closeDialog() {
        this.purItemBatchList.forEach(item => {
          item.purNum = 0;
        });
        this.receiveDialog = false
        this.putStorageDialog = false
      },
      operation(rowIndex, row){
        this.tips.ConfirmModal('确认移除文件名【' + row.fileName + '】吗？', () => {
          let param = {
            id: row.id
          }
          let success = data => {
            if (data.code === "OK") {
              this.$message.success("删除成功")
               this.purchaseContact()
            } else {
              this.$message.error(data.msg)
            }
          }
          this.api.invoiceResourceDelete(param, success)
        });

      },
      //查看入库详情
      handleOperation(rowIndex, row, methodName) {
        let param = {
          purOrderItemId: row.id
        }
        let success = data => {
          if (data.code === "OK") {
            this.houseDetail = data.data;
            this.putStorageDialog = true
          } else {
            this.$messahe.error(data.msg)
          }
        }
        this.api.purBatchItem(param, success)
      }
      ,
      //确定
      btnConfirm() {
        this.receiveDialog = true;
      }
      ,
      //生成word合同
      generate() {
        axios({
          method: 'post',
          url: '/api/erp/v1/contract/create',
          data: {
            purBillsId: this.entityInfo.purBillsId,
            companyName: this.entityInfo.companyName,
            supplyName: this.entityInfo.supplyName,
            supplyAddress: this.entityInfo.supplyAddress,
            supplyContact: this.entityInfo.supplyContact,
            supplyMobile: this.entityInfo.supplyMobile,
            depotAddress: this.entityInfo.depotAddress,
            supplyAccount: this.entityInfo.supplyAccount,
            supplyAccountName: this.entityInfo.supplyAccountName,
            depotName:this.entityInfo.depotName,
            depotPerson:this.entityInfo.depotPerson,
            depotPhone:this.entityInfo.depotPhone,
            items: this.purchaseItemTable.dataArray
          },
          responseType: 'arraybuffer'
        }).then(res => {
          let _data = res.data
          let url = window.URL.createObjectURL(new Blob([_data], {type: 'application/msword'}))
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          let fileName = this.$route.query.purBillsId
          link.setAttribute('download', fileName + '.docx');
          document.body.appendChild(link);
          link.click();
        });
        setTimeout(() => {
          this.$emit('closeDialog')
        }, 1000)
      }
      ,
      buyAudit() {
        this.auditDialog = true;
      }
      ,
      submitForm(value) {
        value.approvalId = this.approval.id;
        value.purBillsId = this.entityInfo.purBillsId;
        let success = data => {
          if (data.code === "OK") {
            this.auditDialog = false;
            this.tips.MessageModal('success', '审批操作成功！');
            this.init();
          } else {
            this.auditDialog = false;
            this.$message.error(data.msg)
          }
        }
        this.api.applyConfirm(value, success)
      }
      ,
      handleReset(formName) {
        this.$refs.form.resetForm(formName);
        this.auditDialog = false;
      }
      ,

      overAudit() {
        this.auditDialog = true;
      }
      ,
    }
  }
</script>
<style scoped>
  .orderinfoContainer .el-form-item {
    margin-bottom: 5px !important;
  }
</style>
<style lang="scss" scoped>
  .orderinfoContainer {
    .orderInfo {
      .iconStyle {
        line-height: 35px;
        font-size: 16px;
        i {
          margin-right: 7px;
        }
        span{
          color:#606266;
          font-size: 15px;
        }
      }
      .orderDetail {
        .el-input {
          width: 220px;
        }

        .el-form-item {
          margin-bottom: 5px !important;
        }
      }

      .confirm {
        width: 85%;
        text-align: center;
        margin-left: 20px;
        padding: 20px;
      }

      .editAudit {
        width: 83%;
        margin-left: 16%;
      }
    }

    .firstAudit {
      width: 450px;
      height: 300px;

      .firstAuditTitle {
        line-height: 40px;
        width: 100%;
        text-align: center;
        background: #eee;
        font-size: 16px;
      }

      .opinion {
        margin: 0 20px;
        padding-top: 20px;

        .el-select {
          width: 60% !important;
        }
        .el-textarea {
          width: 60% !important;
        }
      }
    }
    .detail-order{

      background: #fff;
      margin-bottom:2px;
      border-left: 2px solid #e8e8e8;
      border-right: 2px solid #e8e8e8;
      border-bottom: 2px solid #e8e8e8;
    }


  }
</style>
